"""
备牙数据学习曲线分析工具 - 图形界面版本
Visual Learning Curve Analyzer - GUI Version

功能：
1. 数据提取：从Excel文件中提取数据
2. 学习曲线分析：单组预测和两组对比
3. 可视化展示：美观的图表和结果
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import tkinter.font as tkFont
from tkinter import *
import os
import sys
import threading
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import pandas as pd
from datetime import datetime
import json

# 导入原有的分析模块
from curve_calc_all import (
    calculate_learning_curve, 
    calculate_learning_rate, 
    read_data_from_csv,
    plot_learning_curves,
    plot_average_learning_curves
)
from extractor import extract_groups_to_csv

class ModernGUI:
    def __init__(self, root):
        self.root = root
        self.setup_window()
        self.setup_styles()
        self.create_widgets()
        self.setup_layout()
        
        # 数据存储
        self.current_data = None
        self.analysis_results = None
        
    def setup_window(self):
        """设置主窗口"""
        self.root.title("备牙数据学习曲线分析工具 v1")
        self.root.geometry("1200x800")
        self.root.minsize(1000, 600)
        
        # 设置窗口图标（如果有的话）
        try:
            self.root.iconbitmap('icon.ico')
        except:
            pass
            
        # 设置主题色彩
        self.colors = {
            'primary': '#2E86AB',      # 主色调 - 蓝色
            'secondary': '#A23B72',    # 次要色 - 紫红色
            'accent': '#F18F01',       # 强调色 - 橙色
            'success': '#C73E1D',      # 成功色 - 红色
            'background': '#F8F9FA',   # 背景色
            'surface': '#FFFFFF',      # 表面色
            'text': '#212529',         # 文本色
            'text_secondary': '#6C757D' # 次要文本色
        }
        
        self.root.configure(bg=self.colors['background'])
        
    def setup_styles(self):
        """设置样式"""
        style = ttk.Style()
        style.theme_use('clam')
        
        # 配置样式
        style.configure('Title.TLabel', 
                       font=('Microsoft YaHei UI', 16, 'bold'),
                       foreground=self.colors['primary'],
                       background=self.colors['background'])
        
        style.configure('Subtitle.TLabel', 
                       font=('Microsoft YaHei UI', 12, 'bold'),
                       foreground=self.colors['text'],
                       background=self.colors['background'])
        
        style.configure('Custom.TButton',
                       font=('Microsoft YaHei UI', 10),
                       foreground=self.colors['surface'],
                       background=self.colors['primary'])
        
        style.map('Custom.TButton',
                 background=[('active', self.colors['secondary'])])
        
        style.configure('Action.TButton',
                       font=('Microsoft YaHei UI', 11, 'bold'),
                       foreground=self.colors['surface'],
                       background=self.colors['accent'])
        
        style.map('Action.TButton',
                 background=[('active', '#E07A00')])
        
    def create_widgets(self):
        """创建所有控件"""
        # 创建主标题
        self.create_header()
        
        # 创建主要内容区域
        self.create_main_content()
        
        # 创建状态栏
        self.create_status_bar()
        
    def create_header(self):
        """创建头部区域"""
        header_frame = tk.Frame(self.root, bg=self.colors['surface'], height=80)
        header_frame.pack(fill='x', padx=0, pady=0)
        header_frame.pack_propagate(False)
        
        # 主标题
        title_label = ttk.Label(header_frame, 
                               text="备牙数据学习曲线分析工具",
                               style='Title.TLabel')
        title_label.pack(pady=(20, 5))
        
        # 副标题
        subtitle_label = ttk.Label(header_frame, 
                                  text="Visual Learning Curve Analyzer - 可视化备牙数据分析平台",
                                  font=('Microsoft YaHei UI', 10),
                                  foreground=self.colors['text_secondary'],
                                  background=self.colors['surface'])
        subtitle_label.pack()
        
        # 添加装饰线
        separator = ttk.Separator(header_frame, orient='horizontal')
        separator.pack(fill='x', padx=20, pady=(10, 0))
        
    def create_main_content(self):
        """创建主内容区域"""
        # 创建主容器
        main_container = tk.Frame(self.root, bg=self.colors['background'])
        main_container.pack(fill='both', expand=True, padx=20, pady=10)
        
        # 创建notebook（标签页）
        self.notebook = ttk.Notebook(main_container)
        self.notebook.pack(fill='both', expand=True)
        
        # 创建各个标签页
        self.create_data_tab()
        self.create_analysis_tab()
        self.create_visualization_tab()
        self.create_settings_tab()
        
    def create_data_tab(self):
        """创建数据管理标签页"""
        data_frame = ttk.Frame(self.notebook)
        self.notebook.add(data_frame, text="📁 数据管理")
        
        # 左侧：文件操作区域
        left_frame = tk.Frame(data_frame, bg=self.colors['background'])
        left_frame.pack(side='left', fill='both', expand=True, padx=(10, 5), pady=10)
        
        # 文件操作标题
        file_title = ttk.Label(left_frame, text="文件操作", style='Subtitle.TLabel')
        file_title.pack(anchor='w', pady=(0, 10))
        
        # Excel数据提取区域
        excel_frame = tk.LabelFrame(left_frame, text=" Excel数据提取 ", 
                                   font=('Microsoft YaHei UI', 10, 'bold'),
                                   fg=self.colors['primary'], bg=self.colors['background'])
        excel_frame.pack(fill='x', pady=(0, 15))
        
        # Excel文件选择
        excel_select_frame = tk.Frame(excel_frame, bg=self.colors['background'])
        excel_select_frame.pack(fill='x', padx=10, pady=10)
        
        tk.Label(excel_select_frame, text="选择Excel文件:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(anchor='w')
        
        excel_path_frame = tk.Frame(excel_select_frame, bg=self.colors['background'])
        excel_path_frame.pack(fill='x', pady=(5, 0))
        
        self.excel_path_var = tk.StringVar()
        excel_entry = tk.Entry(excel_path_frame, textvariable=self.excel_path_var,
                              font=('Microsoft YaHei UI', 9), width=50)
        excel_entry.pack(side='left', fill='x', expand=True)
        
        ttk.Button(excel_path_frame, text="浏览", style='Custom.TButton',
                  command=self.browse_excel_file).pack(side='right', padx=(5, 0))
        
        # 工作表选择
        sheet_frame = tk.Frame(excel_frame, bg=self.colors['background'])
        sheet_frame.pack(fill='x', padx=10, pady=(10, 0))
        
        tk.Label(sheet_frame, text="工作表:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(anchor='w')
        
        self.sheet_var = tk.StringVar()
        self.sheet_combo = ttk.Combobox(sheet_frame, textvariable=self.sheet_var,
                                       font=('Microsoft YaHei UI', 9), state='readonly')
        self.sheet_combo.pack(fill='x', pady=(5, 0))
        
        # 提取按钮
        ttk.Button(excel_frame, text="提取数据到CSV", style='Action.TButton',
                  command=self.extract_excel_data).pack(pady=15)
        
        # CSV文件操作区域
        csv_frame = tk.LabelFrame(left_frame, text=" CSV文件管理 ", 
                                 font=('Microsoft YaHei UI', 10, 'bold'),
                                 fg=self.colors['primary'], bg=self.colors['background'])
        csv_frame.pack(fill='x', pady=(0, 15))
        
        # IR组文件
        ir_frame = tk.Frame(csv_frame, bg=self.colors['background'])
        ir_frame.pack(fill='x', padx=10, pady=5)
        
        tk.Label(ir_frame, text="IR组数据文件:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(anchor='w')
        
        ir_path_frame = tk.Frame(ir_frame, bg=self.colors['background'])
        ir_path_frame.pack(fill='x', pady=(5, 0))
        
        self.ir_path_var = tk.StringVar(value="IR组.csv")
        ir_entry = tk.Entry(ir_path_frame, textvariable=self.ir_path_var,
                           font=('Microsoft YaHei UI', 9))
        ir_entry.pack(side='left', fill='x', expand=True)
        
        ttk.Button(ir_path_frame, text="浏览", style='Custom.TButton',
                  command=lambda: self.browse_csv_file(self.ir_path_var)).pack(side='right', padx=(5, 0))
        
        # MR组文件
        mr_frame = tk.Frame(csv_frame, bg=self.colors['background'])
        mr_frame.pack(fill='x', padx=10, pady=5)
        
        tk.Label(mr_frame, text="MR组数据文件:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(anchor='w')
        
        mr_path_frame = tk.Frame(mr_frame, bg=self.colors['background'])
        mr_path_frame.pack(fill='x', pady=(5, 0))
        
        self.mr_path_var = tk.StringVar(value="MR组.csv")
        mr_entry = tk.Entry(mr_path_frame, textvariable=self.mr_path_var,
                           font=('Microsoft YaHei UI', 9))
        mr_entry.pack(side='left', fill='x', expand=True)
        
        ttk.Button(mr_path_frame, text="浏览", style='Custom.TButton',
                  command=lambda: self.browse_csv_file(self.mr_path_var)).pack(side='right', padx=(5, 0))
        
        # 右侧：数据预览区域
        right_frame = tk.Frame(data_frame, bg=self.colors['background'])
        right_frame.pack(side='right', fill='both', expand=True, padx=(5, 10), pady=10)
        
        # 数据预览标题
        preview_title = ttk.Label(right_frame, text="数据预览", style='Subtitle.TLabel')
        preview_title.pack(anchor='w', pady=(0, 10))
        
        # 数据预览框
        preview_frame = tk.LabelFrame(right_frame, text=" 当前数据 ", 
                                     font=('Microsoft YaHei UI', 10, 'bold'),
                                     fg=self.colors['primary'], bg=self.colors['background'])
        preview_frame.pack(fill='both', expand=True)
        
        # 创建Treeview用于数据预览
        tree_frame = tk.Frame(preview_frame, bg=self.colors['background'])
        tree_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 创建滚动条
        tree_scroll_y = ttk.Scrollbar(tree_frame)
        tree_scroll_y.pack(side='right', fill='y')
        
        tree_scroll_x = ttk.Scrollbar(tree_frame, orient='horizontal')
        tree_scroll_x.pack(side='bottom', fill='x')
        
        # 创建Treeview
        self.data_tree = ttk.Treeview(tree_frame, 
                                     yscrollcommand=tree_scroll_y.set,
                                     xscrollcommand=tree_scroll_x.set,
                                     height=15)
        self.data_tree.pack(fill='both', expand=True)
        
        tree_scroll_y.config(command=self.data_tree.yview)
        tree_scroll_x.config(command=self.data_tree.xview)
        
        # 预览按钮
        preview_btn_frame = tk.Frame(preview_frame, bg=self.colors['background'])
        preview_btn_frame.pack(fill='x', padx=10, pady=(0, 10))
        
        ttk.Button(preview_btn_frame, text="预览IR组数据", style='Custom.TButton',
                  command=lambda: self.preview_data('ir')).pack(side='left', padx=(0, 5))
        
        ttk.Button(preview_btn_frame, text="预览MR组数据", style='Custom.TButton',
                  command=lambda: self.preview_data('mr')).pack(side='left', padx=5)
        
        ttk.Button(preview_btn_frame, text="清空预览", style='Custom.TButton',
                  command=self.clear_preview).pack(side='right')
    
    def create_analysis_tab(self):
        """创建分析配置标签页"""
        analysis_frame = ttk.Frame(self.notebook)
        self.notebook.add(analysis_frame, text="⚙️ 分析配置")
        
        # 主容器
        main_frame = tk.Frame(analysis_frame, bg=self.colors['background'])
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 左侧：分析模式选择
        left_frame = tk.Frame(main_frame, bg=self.colors['background'])
        left_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        # 分析模式
        mode_frame = tk.LabelFrame(left_frame, text=" 分析模式 ", 
                                  font=('Microsoft YaHei UI', 12, 'bold'),
                                  fg=self.colors['primary'], bg=self.colors['background'])
        mode_frame.pack(fill='x', pady=(0, 20))
        
        self.analysis_mode = tk.StringVar(value="single")
        
        # 单组分析模式
        single_frame = tk.Frame(mode_frame, bg=self.colors['background'])
        single_frame.pack(fill='x', padx=15, pady=10)
        
        single_radio = tk.Radiobutton(single_frame, text="单组预测曲线分析", 
                                     variable=self.analysis_mode, value="single",
                                     font=('Microsoft YaHei UI', 11), 
                                     bg=self.colors['background'],
                                     activebackground=self.colors['background'],
                                     command=self.on_mode_change)
        single_radio.pack(anchor='w')
        
        single_desc = tk.Label(single_frame, 
                              text="为单个数据文件中的每组数据生成独立的学习曲线预测",
                              font=('Microsoft YaHei UI', 9), 
                              fg=self.colors['text_secondary'],
                              bg=self.colors['background'])
        single_desc.pack(anchor='w', padx=20, pady=(2, 0))
        
        # 对比分析模式
        compare_frame = tk.Frame(mode_frame, bg=self.colors['background'])
        compare_frame.pack(fill='x', padx=15, pady=10)
        
        compare_radio = tk.Radiobutton(compare_frame, text="两组对比分析", 
                                      variable=self.analysis_mode, value="compare",
                                      font=('Microsoft YaHei UI', 11), 
                                      bg=self.colors['background'],
                                      activebackground=self.colors['background'],
                                      command=self.on_mode_change)
        compare_radio.pack(anchor='w')
        
        compare_desc = tk.Label(compare_frame, 
                               text="比较IR组和MR组的平均学习曲线，显示统计差异",
                               font=('Microsoft YaHei UI', 9), 
                               fg=self.colors['text_secondary'],
                               bg=self.colors['background'])
        compare_desc.pack(anchor='w', padx=20, pady=(2, 0))
        
        # 分析参数
        params_frame = tk.LabelFrame(left_frame, text=" 分析参数 ", 
                                    font=('Microsoft YaHei UI', 12, 'bold'),
                                    fg=self.colors['primary'], bg=self.colors['background'])
        params_frame.pack(fill='x', pady=(0, 20))
        
        # 最大训练次数
        max_training_frame = tk.Frame(params_frame, bg=self.colors['background'])
        max_training_frame.pack(fill='x', padx=15, pady=10)
        
        tk.Label(max_training_frame, text="最大训练次数:", 
                font=('Microsoft YaHei UI', 10), bg=self.colors['background']).pack(anchor='w')
        
        self.max_training_var = tk.IntVar(value=30)
        max_training_spinbox = tk.Spinbox(max_training_frame, from_=10, to=100, 
                                         textvariable=self.max_training_var,
                                         font=('Microsoft YaHei UI', 10), width=15)
        max_training_spinbox.pack(anchor='w', pady=(5, 0))
        
        # 图表标题
        title_frame = tk.Frame(params_frame, bg=self.colors['background'])
        title_frame.pack(fill='x', padx=15, pady=10)
        
        tk.Label(title_frame, text="图表标题:", 
                font=('Microsoft YaHei UI', 10), bg=self.colors['background']).pack(anchor='w')
        
        self.chart_title_var = tk.StringVar()
        title_entry = tk.Entry(title_frame, textvariable=self.chart_title_var,
                              font=('Microsoft YaHei UI', 10), width=40)
        title_entry.pack(fill='x', pady=(5, 0))
        
        # 输出选项
        output_frame = tk.LabelFrame(left_frame, text=" 输出选项 ", 
                                    font=('Microsoft YaHei UI', 12, 'bold'),
                                    fg=self.colors['primary'], bg=self.colors['background'])
        output_frame.pack(fill='x')
        
        self.save_csv_var = tk.BooleanVar(value=True)
        self.save_plot_var = tk.BooleanVar(value=True)
        
        csv_check = tk.Checkbutton(output_frame, text="保存CSV结果文件", 
                                  variable=self.save_csv_var,
                                  font=('Microsoft YaHei UI', 10), 
                                  bg=self.colors['background'],
                                  activebackground=self.colors['background'])
        csv_check.pack(anchor='w', padx=15, pady=5)
        
        plot_check = tk.Checkbutton(output_frame, text="保存图像文件", 
                                   variable=self.save_plot_var,
                                   font=('Microsoft YaHei UI', 10), 
                                   bg=self.colors['background'],
                                   activebackground=self.colors['background'])
        plot_check.pack(anchor='w', padx=15, pady=5)
        
        # 右侧：单组分析特殊选项
        right_frame = tk.Frame(main_frame, bg=self.colors['background'])
        right_frame.pack(side='right', fill='both', expand=True, padx=(10, 0))
        
        # 单组分析选项
        self.single_options_frame = tk.LabelFrame(right_frame, text=" 单组分析选项 ", 
                                                 font=('Microsoft YaHei UI', 12, 'bold'),
                                                 fg=self.colors['primary'], bg=self.colors['background'])
        self.single_options_frame.pack(fill='x', pady=(0, 20))
        
        # 数据文件选择
        single_file_frame = tk.Frame(self.single_options_frame, bg=self.colors['background'])
        single_file_frame.pack(fill='x', padx=15, pady=10)
        
        tk.Label(single_file_frame, text="选择分析文件:", 
                font=('Microsoft YaHei UI', 10), bg=self.colors['background']).pack(anchor='w')
        
        self.single_file_var = tk.StringVar(value="ir")
        
        ir_radio = tk.Radiobutton(single_file_frame, text="使用IR组数据", 
                                 variable=self.single_file_var, value="ir",
                                 font=('Microsoft YaHei UI', 10), 
                                 bg=self.colors['background'],
                                 activebackground=self.colors['background'])
        ir_radio.pack(anchor='w', pady=2)
        
        mr_radio = tk.Radiobutton(single_file_frame, text="使用MR组数据", 
                                 variable=self.single_file_var, value="mr",
                                 font=('Microsoft YaHei UI', 10), 
                                 bg=self.colors['background'],
                                 activebackground=self.colors['background'])
        mr_radio.pack(anchor='w', pady=2)
        
        custom_radio = tk.Radiobutton(single_file_frame, text="使用自定义文件", 
                                     variable=self.single_file_var, value="custom",
                                     font=('Microsoft YaHei UI', 10), 
                                     bg=self.colors['background'],
                                     activebackground=self.colors['background'])
        custom_radio.pack(anchor='w', pady=2)
        
        # 自定义文件路径
        custom_path_frame = tk.Frame(single_file_frame, bg=self.colors['background'])
        custom_path_frame.pack(fill='x', pady=(5, 0))
        
        self.custom_file_var = tk.StringVar()
        custom_entry = tk.Entry(custom_path_frame, textvariable=self.custom_file_var,
                               font=('Microsoft YaHei UI', 9))
        custom_entry.pack(side='left', fill='x', expand=True)
        
        ttk.Button(custom_path_frame, text="浏览", style='Custom.TButton',
                  command=lambda: self.browse_csv_file(self.custom_file_var)).pack(side='right', padx=(5, 0))
        
        # 执行分析按钮
        btn_frame = tk.Frame(right_frame, bg=self.colors['background'])
        btn_frame.pack(fill='x', pady=20)
        
        self.analyze_btn = ttk.Button(btn_frame, text="🚀 开始分析", style='Action.TButton',
                                     command=self.run_analysis)
        self.analyze_btn.pack(expand=True)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(btn_frame, variable=self.progress_var, 
                                           mode='determinate')
        self.progress_bar.pack(fill='x', pady=(10, 0))
        self.progress_bar.pack_forget()  # 初始隐藏
    
    def create_visualization_tab(self):
        """创建可视化结果标签页"""
        viz_frame = ttk.Frame(self.notebook)
        self.notebook.add(viz_frame, text="📊 可视化结果")
        
        # 主容器
        main_container = tk.Frame(viz_frame, bg=self.colors['background'])
        main_container.pack(fill='both', expand=True)
        
        # 工具栏
        toolbar_frame = tk.Frame(main_container, bg=self.colors['surface'], height=50)
        toolbar_frame.pack(fill='x', padx=0, pady=0)
        toolbar_frame.pack_propagate(False)
        
        # 工具栏按钮
        ttk.Button(toolbar_frame, text="💾 保存图表", style='Custom.TButton',
                  command=self.save_current_plot).pack(side='left', padx=10, pady=10)
        
        ttk.Button(toolbar_frame, text="🔄 刷新", style='Custom.TButton',
                  command=self.refresh_plot).pack(side='left', padx=5, pady=10)
        
        ttk.Button(toolbar_frame, text="📈 导出数据", style='Custom.TButton',
                  command=self.export_data).pack(side='left', padx=5, pady=10)
        
        # 图表区域
        chart_frame = tk.Frame(main_container, bg=self.colors['background'])
        chart_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 创建matplotlib图表
        self.figure = Figure(figsize=(12, 8), dpi=100, facecolor='white')
        self.canvas = FigureCanvasTkAgg(self.figure, chart_frame)
        self.canvas.get_tk_widget().pack(fill='both', expand=True)
        
        # 初始化空图表
        self.init_empty_plot()
    
    def create_settings_tab(self):
        """创建设置标签页"""
        settings_frame = ttk.Frame(self.notebook)
        self.notebook.add(settings_frame, text="⚙️ 设置")
        
        # 主容器
        main_frame = tk.Frame(settings_frame, bg=self.colors['background'])
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 图表设置
        chart_settings_frame = tk.LabelFrame(main_frame, text=" 图表设置 ", 
                                            font=('Microsoft YaHei UI', 12, 'bold'),
                                            fg=self.colors['primary'], bg=self.colors['background'])
        chart_settings_frame.pack(fill='x', pady=(0, 20))
        
        # 图表尺寸
        size_frame = tk.Frame(chart_settings_frame, bg=self.colors['background'])
        size_frame.pack(fill='x', padx=15, pady=10)
        
        tk.Label(size_frame, text="图表尺寸:", 
                font=('Microsoft YaHei UI', 10), bg=self.colors['background']).pack(anchor='w')
        
        size_sub_frame = tk.Frame(size_frame, bg=self.colors['background'])
        size_sub_frame.pack(fill='x', pady=(5, 0))
        
        tk.Label(size_sub_frame, text="宽度:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(side='left')
        
        self.chart_width_var = tk.DoubleVar(value=12.0)
        width_spinbox = tk.Spinbox(size_sub_frame, from_=8.0, to=20.0, increment=0.5,
                                  textvariable=self.chart_width_var,
                                  font=('Microsoft YaHei UI', 9), width=8)
        width_spinbox.pack(side='left', padx=5)
        
        tk.Label(size_sub_frame, text="高度:", 
                font=('Microsoft YaHei UI', 9), bg=self.colors['background']).pack(side='left', padx=(20, 0))
        
        self.chart_height_var = tk.DoubleVar(value=8.0)
        height_spinbox = tk.Spinbox(size_sub_frame, from_=6.0, to=15.0, increment=0.5,
                                   textvariable=self.chart_height_var,
                                   font=('Microsoft YaHei UI', 9), width=8)
        height_spinbox.pack(side='left', padx=5)
        
        # 关于信息
        about_frame = tk.LabelFrame(main_frame, text=" 关于 ", 
                                   font=('Microsoft YaHei UI', 12, 'bold'),
                                   fg=self.colors['primary'], bg=self.colors['background'])
        about_frame.pack(fill='x')
        
        about_text = """
备牙数据学习曲线分析工具 v2.0

功能特点：
• 支持Excel数据提取和CSV格式分析
• 基于Wright学习曲线模型的专业算法
• 提供单组预测和两组对比两种分析模式
• 美观的可视化图表和详细的统计结果
• 支持批量数据处理和结果导出

开发信息：
• 基于Python开发的专业数据分析工具
• 使用matplotlib进行高质量图表绘制
• 支持中文界面和中文数据处理
• 提供完整的错误处理和用户提示

版本：v2.0
更新日期：2025年7月
        """
        
        about_label = tk.Label(about_frame, text=about_text,
                              font=('Microsoft YaHei UI', 9), 
                              fg=self.colors['text'],
                              bg=self.colors['background'],
                              justify='left')
        about_label.pack(anchor='w', padx=15, pady=15)
    
    def create_status_bar(self):
        """创建状态栏"""
        self.status_frame = tk.Frame(self.root, bg=self.colors['primary'], height=30)
        self.status_frame.pack(fill='x', side='bottom')
        self.status_frame.pack_propagate(False)
        
        self.status_var = tk.StringVar(value="就绪")
        self.status_label = tk.Label(self.status_frame, textvariable=self.status_var,
                                    font=('Microsoft YaHei UI', 9), 
                                    fg=self.colors['surface'],
                                    bg=self.colors['primary'])
        self.status_label.pack(side='left', padx=10, pady=5)
        
        # 右侧显示时间
        self.time_var = tk.StringVar()
        self.time_label = tk.Label(self.status_frame, textvariable=self.time_var,
                                  font=('Microsoft YaHei UI', 9), 
                                  fg=self.colors['surface'],
                                  bg=self.colors['primary'])
        self.time_label.pack(side='right', padx=10, pady=5)
        
        self.update_time()
    
    def setup_layout(self):
        """设置布局"""
        # 初始化一些默认状态
        self.on_mode_change()
    
    def update_time(self):
        """更新时间显示"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.time_var.set(current_time)
        self.root.after(1000, self.update_time)
    
    def update_status(self, message):
        """更新状态栏信息"""
        self.status_var.set(message)
        self.root.update_idletasks()
    
    def on_mode_change(self):
        """分析模式改变时的处理"""
        mode = self.analysis_mode.get()
        if mode == "single":
            self.single_options_frame.pack(fill='x', pady=(0, 20))
        else:
            self.single_options_frame.pack_forget()
    
    def browse_excel_file(self):
        """浏览Excel文件"""
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel files", "*.xlsx *.xls"), ("All files", "*.*")]
        )
        if file_path:
            self.excel_path_var.set(file_path)
            self.load_excel_sheets()
    
    def browse_csv_file(self, var):
        """浏览CSV文件"""
        file_path = filedialog.askopenfilename(
            title="选择CSV文件",
            filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
        )
        if file_path:
            var.set(file_path)
    
    def load_excel_sheets(self):
        """加载Excel工作表"""
        excel_path = self.excel_path_var.get()
        if not excel_path or not os.path.exists(excel_path):
            return
        
        try:
            self.update_status("正在读取Excel文件...")
            sheets = pd.read_excel(excel_path, sheet_name=None)
            sheet_names = list(sheets.keys())
            self.sheet_combo['values'] = sheet_names
            if sheet_names:
                self.sheet_combo.set(sheet_names[0])
            self.update_status(f"成功加载 {len(sheet_names)} 个工作表")
        except Exception as e:
            messagebox.showerror("错误", f"读取Excel文件失败：{str(e)}")
            self.update_status("Excel文件读取失败")
    
    def extract_excel_data(self):
        """提取Excel数据"""
        excel_path = self.excel_path_var.get()
        sheet_name = self.sheet_var.get()
        
        if not excel_path or not os.path.exists(excel_path):
            messagebox.showerror("错误", "请先选择有效的Excel文件")
            return
        
        if not sheet_name:
            messagebox.showerror("错误", "请选择工作表")
            return
        
        try:
            self.update_status("正在提取数据...")
            output_csv = f"{sheet_name}.csv"
            extract_groups_to_csv(excel_path, sheet_name, output_csv)
            
            messagebox.showinfo("成功", f"数据已成功提取到 {output_csv}")
            self.update_status(f"数据提取完成：{output_csv}")
            
            # 自动设置文件路径
            if "IR" in sheet_name.upper():
                self.ir_path_var.set(output_csv)
            elif "MR" in sheet_name.upper():
                self.mr_path_var.set(output_csv)
                
        except Exception as e:
            messagebox.showerror("错误", f"数据提取失败：{str(e)}")
            self.update_status("数据提取失败")
    
    def preview_data(self, data_type):
        """预览数据"""
        if data_type == 'ir':
            file_path = self.ir_path_var.get()
            title = "IR组数据"
        else:
            file_path = self.mr_path_var.get()
            title = "MR组数据"
        
        if not file_path or not os.path.exists(file_path):
            messagebox.showerror("错误", f"文件不存在：{file_path}")
            return
        
        try:
            self.update_status(f"正在加载{title}...")
            data_groups = read_data_from_csv(file_path)
            
            # 清空当前数据
            self.clear_preview()
            
            # 设置列
            columns = [f"数据点{i+1}" for i in range(max(len(group) for group in data_groups) if data_groups else 0)]
            self.data_tree['columns'] = columns
            self.data_tree['show'] = 'tree headings'
            
            # 设置列标题
            self.data_tree.heading('#0', text='组别', anchor='w')
            self.data_tree.column('#0', width=80, minwidth=80)
            
            for col in columns:
                self.data_tree.heading(col, text=col, anchor='center')
                self.data_tree.column(col, width=80, minwidth=80)
            
            # 插入数据
            for i, group in enumerate(data_groups):
                values = group + [''] * (len(columns) - len(group))  # 填充空值
                self.data_tree.insert('', 'end', text=f'第{i+1}组', values=values)
            
            self.update_status(f"{title}加载完成，共{len(data_groups)}组数据")
            
        except Exception as e:
            messagebox.showerror("错误", f"数据加载失败：{str(e)}")
            self.update_status("数据加载失败")
    
    def clear_preview(self):
        """清空预览"""
        for item in self.data_tree.get_children():
            self.data_tree.delete(item)
        self.data_tree['columns'] = ()
    
    def run_analysis(self):
        """运行分析"""
        # 禁用分析按钮
        self.analyze_btn.config(state='disabled')
        self.progress_bar.pack(fill='x', pady=(10, 0))
        self.progress_var.set(0)
        
        # 在新线程中运行分析
        threading.Thread(target=self._run_analysis_thread, daemon=True).start()
    
    def _run_analysis_thread(self):
        """分析线程"""
        try:
            mode = self.analysis_mode.get()
            max_training = self.max_training_var.get()
            title = self.chart_title_var.get()
            save_csv = self.save_csv_var.get()
            save_plot = self.save_plot_var.get()
            
            self.root.after(0, lambda: self.update_status("正在分析数据..."))
            self.root.after(0, lambda: self.progress_var.set(20))
            
            if mode == "single":
                # 单组分析
                file_choice = self.single_file_var.get()
                if file_choice == "ir":
                    csv_file_path = self.ir_path_var.get()
                elif file_choice == "mr":
                    csv_file_path = self.mr_path_var.get()
                else:  # custom
                    csv_file_path = self.custom_file_var.get()
                
                if not csv_file_path or not os.path.exists(csv_file_path):
                    self.root.after(0, lambda: messagebox.showerror("错误", f"文件不存在：{csv_file_path}"))
                    return
                
                # 读取数据
                data_groups = read_data_from_csv(csv_file_path)
                if not data_groups:
                    self.root.after(0, lambda: messagebox.showerror("错误", "未找到有效数据"))
                    return
                
                self.root.after(0, lambda: self.progress_var.set(50))
                
                # 设置标题
                if not title:
                    file_name = os.path.splitext(os.path.basename(csv_file_path))[0]
                    title = f"{file_name}学习曲线预测"
                
                # 执行分析
                result = plot_learning_curves(
                    data_groups=data_groups,
                    csv_file_path=csv_file_path,
                    max_training=max_training,
                    title=title,
                    figure_size=(self.chart_width_var.get(), self.chart_height_var.get()),
                    save_csv=save_csv,
                    save_plot=save_plot
                )
                
                self.root.after(0, lambda: self.progress_var.set(80))
                
                # 更新图表
                self.root.after(0, lambda: self._update_single_plot(result, title, max_training))
                
            else:
                # 对比分析
                ir_path = self.ir_path_var.get()
                mr_path = self.mr_path_var.get()
                
                if not title:
                    title = "IR组与MR组平均学习曲线对比"
                
                self.root.after(0, lambda: self.progress_var.set(50))
                
                # 执行对比分析
                result = plot_average_learning_curves(
                    ir_csv_path=ir_path,
                    mr_csv_path=mr_path,
                    max_training=max_training,
                    title=title,
                    figure_size=(self.chart_width_var.get(), self.chart_height_var.get()),
                    save_csv=save_csv,
                    save_plot=save_plot
                )
                
                self.root.after(0, lambda: self.progress_var.set(80))
                
                # 更新图表
                self.root.after(0, lambda: self._update_compare_plot(result, title, max_training))
            
            self.root.after(0, lambda: self.progress_var.set(100))
            self.root.after(0, lambda: self.update_status("分析完成"))
            self.root.after(0, lambda: messagebox.showinfo("完成", "数据分析完成！"))
            
        except Exception as e:
            self.root.after(0, lambda: messagebox.showerror("错误", f"分析失败：{str(e)}"))
            self.root.after(0, lambda: self.update_status("分析失败"))
        finally:
            # 重新启用按钮并隐藏进度条
            self.root.after(0, lambda: self.analyze_btn.config(state='normal'))
            self.root.after(0, lambda: self.progress_bar.pack_forget())
    
    def _update_single_plot(self, result, title, max_training):
        """更新单组分析图表"""
        if not result:
            return
        
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        
        # 绘制各组曲线
        colors = plt.cm.tab10(np.linspace(0, 1, len(result['valid_groups'])))
        
        for i, (prediction, group_info) in enumerate(zip(result['predictions'], result['valid_groups'])):
            group_num, y1, LR = group_info
            x_values = result['x_values']
            
            ax.plot(x_values, prediction, color=colors[i], linewidth=1.5,
                   label=f'组 {group_num} (y1={y1:.2f}, LR={LR:.4f})')
        
        # 设置图表
        ax.set_title(title, fontsize=14, fontweight='bold')
        ax.set_xlabel("训练次数 (x)", fontsize=12)
        ax.set_ylabel("分数", fontsize=12)
        ax.grid(True, linestyle="--", alpha=0.7)
        ax.set_xticks(np.arange(0, max_training + 1, 5))
        ax.legend(loc='best')
        ax.set_ylim(bottom=None, top=100)
        
        self.figure.tight_layout()
        self.canvas.draw()
        
        # 切换到可视化标签页
        self.notebook.select(2)
    
    def _update_compare_plot(self, result, title, max_training):
        """更新对比分析图表"""
        if not result:
            return
        
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        
        colors = ['#1f77b4', '#ff7f0e']  # 蓝色和橙色
        labels = ['IR组', 'MR组']
        
        for i, (group_name, color, label) in enumerate(zip(['ir组', 'mr组'], colors, labels)):
            if group_name in result:
                group_data = result[group_name]
                x_values = np.array(group_data['x_values'])
                avg_predictions = np.array(group_data['average_predictions'])
                std_predictions = np.array(group_data['std_predictions'])
                
                # 绘制平均曲线
                ax.plot(x_values, avg_predictions, color=color, linewidth=2.5,
                       label=f'{label}平均曲线 (n={group_data["valid_count"]})', 
                       marker='o', markersize=4)
                
                # 绘制标准差区域
                ax.fill_between(x_values,
                               avg_predictions - std_predictions,
                               avg_predictions + std_predictions,
                               color=color, alpha=0.2,
                               label=f'{label}标准差范围')
        
        # 设置图表
        ax.set_title(title, fontsize=14, fontweight='bold')
        ax.set_xlabel("训练次数 (x)", fontsize=12)
        ax.set_ylabel("分数", fontsize=12)
        ax.grid(True, linestyle="--", alpha=0.7)
        ax.set_xticks(np.arange(0, max_training + 1, 5))
        ax.legend(loc='best')
        ax.set_ylim(bottom=None, top=100)
        
        self.figure.tight_layout()
        self.canvas.draw()
        
        # 切换到可视化标签页
        self.notebook.select(2)
    
    def init_empty_plot(self):
        """初始化空图表"""
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        
        ax.text(0.5, 0.5, '暂无数据\n请先进行数据分析', 
               horizontalalignment='center', verticalalignment='center',
               transform=ax.transAxes, fontsize=16, 
               color=self.colors['text_secondary'])
        
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 1)
        ax.axis('off')
        
        self.canvas.draw()
    
    def save_current_plot(self):
        """保存当前图表"""
        file_path = filedialog.asksaveasfilename(
            title="保存图表",
            defaultextension=".png",
            filetypes=[
                ("PNG files", "*.png"),
                ("PDF files", "*.pdf"),
                ("SVG files", "*.svg"),
                ("All files", "*.*")
            ]
        )
        if file_path:
            try:
                self.figure.savefig(file_path, dpi=300, bbox_inches='tight')
                messagebox.showinfo("成功", f"图表已保存到：{file_path}")
                self.update_status(f"图表已保存：{os.path.basename(file_path)}")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败：{str(e)}")
    
    def refresh_plot(self):
        """刷新图表"""
        self.canvas.draw()
        self.update_status("图表已刷新")
    
    def export_data(self):
        """导出数据"""
        # 这里可以实现数据导出功能
        messagebox.showinfo("提示", "数据导出功能开发中...")


def main():
    """主函数"""
    root = tk.Tk()
    
    # 设置DPI感知（Windows）
    try:
        from ctypes import windll
        windll.shcore.SetProcessDpiAwareness(1)
    except:
        pass
    
    app = ModernGUI(root)
    root.mainloop()


if __name__ == "__main__":
    main()
